package com.ethan.cj.ssm.controller;

import com.ethan.cj.ssm.entity.People;
import com.ethan.cj.ssm.service.LoginService;
import com.ethan.cj.ssm.service.PeopleService;
import com.ethan.cj.ssm.util.IpUtil;
import com.ethan.cj.ssm.util.JsonUtil;
import lombok.extern.log4j.Log4j;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.awt.ModalExclude;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;


@Controller
@Log4j
/**
 * 注册页面和登陆页面
 */
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private PeopleService peopleService;

    /**
     * 进入登陆页面
     * @return
     */
    @RequestMapping("getlogin")
    public String getlogin(){
        return "login";
    }

    /**
     * 请求退出主界面
     *
     * @param request HttpServlet请求
     * @return 登录页面路径
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("peopleinfo");
        return "login";
    }

    /**
     * 登录校验
     *
     * @param peopleJson 用户请求Json数据
     * @param request  HttpServlet请求
     * @return 返回JSON结果信息
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<Object, Object> doLogin(@RequestParam("people") String peopleJson, HttpServletRequest request) {
        Map map = JsonUtil.parseObject(peopleJson, Map.class);
        return loginService.getPeopleByPname(map,request);
    }

    /**
     * 跳转至登陆成功页面
     * @param model
     * @return
     */
    @RequestMapping("success")
    public String success(Model model,HttpServletRequest request){
        HttpSession session=request.getSession();
        People people=(People) session.getAttribute("peopleinfo");
        people.setLastLoginTime(new Date());
        String ip=IpUtil.getIpAddr(request);
        System.out.println(people.toString());
        int rst=peopleService.updateLogin(people);

        return "ceshi";
    }

    /**
     * 用户跳转至注册页面
     * @param
     * @return
     */
    @RequestMapping("register")
    public String register() {
        return "register";
    }

    @RequestMapping("Weclome")
    public String Weclome(){
        return "Weclome";
    }

}